Skip to main content

Ternary Expression

The ternary operator ? : picks one of two values based on a condition.

Basic Usage

println(true ? "Hello" : "World")
print(2 > 1 ? "Hello" : "World")

Output:

Hello
Hello

When the condition before ? is true, the left value is used. When false, the right value after : is used.

Assignment

var x: int = (43 == 43) ? 10 : 20
print(x)

Output:

10

If the condition is true, 10 is assigned. Otherwise 20.

Parentheses around the condition are optional. Use them for readability:

var a: int = 10
var b: int = 5
var r = a > b ? a + 1 : b + 1        /; works
var r2 = (a > b) ? (a + 1) : (b + 1)  /; also works, clearer
print(r)
print(r2)

Returning from Functions

fun max(a: int, b: int) -> int {
  return a > b ? a : b
}
print(max(10, 20))

Output:

20

If a > b is true, a is returned. Otherwise, b is returned.